package com.mf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mf.entity.bo.RosterBo;
import com.mf.entity.dto.RosterDto;
import com.mf.entity.dto.roster.RosterChangeJobDto;
import com.mf.entity.dto.roster.RosterChangeTypeDto;
import com.mf.entity.dto.roster.RosterLeaveDto;
import com.mf.entity.request.roster.RosterRequest;
import com.mf.entity.vo.RosterVo;
import com.mf.entity.vo.dept.DeptVo;
import com.mf.entity.vo.dept.PositionVo;
import com.mf.enums.roster.RosterStatusEnum;
import com.mf.enums.roster.RosterTypeEnum;
import com.mf.mapper.RosterMapper;
import com.mf.service.IDeptService;
import com.mf.service.IPositionService;
import com.mf.service.IRosterService;
import io.github.heollhai.common.config.exceptions.GraceException;
import io.github.heollhai.common.entity.vo.date.StartAndEndVo;
import io.github.heollhai.common.utils.DateUtil;
import io.github.heollhai.common.utils.MybatisPlusUtils;
import io.github.heollhai.common.utils.VerifyUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 服务实现类
 *
 * @author mf
 * @since 2024-09-01
 */
@Service
public class RosterServiceImpl extends ServiceImpl<RosterMapper, RosterBo> implements IRosterService {
    @Resource
    private RosterMapper rosterMapper;


    /**
     * 根据岗位id是否有对应员工
     */
    @Override
    public Boolean isJobIdByUser(Integer jobId) {
        LambdaQueryWrapper<RosterBo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RosterBo::getEntryJobId, jobId);
        RosterBo rosterBo = rosterMapper.selectOne(wrapper);
        return VerifyUtils.isNotEmpty(rosterBo);
    }

    /**
     * 修改员工岗位
     */
    @Override
    public Integer changeJob(RosterChangeJobDto rosterChangeJobDto) {
        final RosterBo rosterBo = new RosterBo();
        BeanUtils.copyProperties(rosterChangeJobDto, rosterBo);
        return rosterMapper.updateById(rosterBo);
    }

    /**
     * 离职
     */
    @Override
    public Integer leave(RosterLeaveDto rosterLeaveDto) {
        final RosterBo rosterBo = getById(rosterLeaveDto.getId());
        if (VerifyUtils.isEmpty(rosterBo)) {
            GraceException.display("没有对应用户信息");
        }
        BeanUtils.copyProperties(rosterLeaveDto, rosterBo);
        rosterBo.setStatus(RosterStatusEnum.LEAVE.getValue());
        return rosterMapper.updateById(rosterBo);
    }

    /**
     * 新增|编辑
     */
    @Override
    public Integer insert(RosterDto rosterDto) {
        final RosterBo rosterBo = new RosterBo();
        BeanUtils.copyProperties(rosterDto, rosterBo);
        if (VerifyUtils.isEmpty(rosterDto.getId())) {
            rosterBo.setStatus(null);
            rosterBo.setEmpNo(generateEmpNo(rosterDto.getType()));
            return rosterMapper.insert(rosterBo);
        } else {
            rosterBo.setEntryDeptId(null);
            rosterBo.setEntryJobId(null);
            rosterBo.setEmpNo(null);
            rosterBo.setIdentityNumber(null);
            rosterBo.setType(null);
            rosterBo.setStatus(null);
            return rosterMapper.updateById(rosterBo);
        }
    }

    /**
     * 生成工号
     */
    public String generateEmpNo(RosterTypeEnum type) {
        final LambdaQueryWrapper<RosterBo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(RosterBo::getEmpNo)
                .eq(RosterBo::getType, type);
        final RosterBo rosterBo = rosterMapper.selectOne(wrapper);
        if (VerifyUtils.isEmpty(rosterBo)) {
            return addEmpNoPrefix(type) + "000010";
        }

        final int length = (type.equals(RosterTypeEnum.TEMPORARY_WORKER) ? 2 : 3);
        int value = Integer.parseInt(rosterBo.getEmpNo().substring(length));

        return addEmpNoPrefix(type) + String.format("%06d", value + 1);
    }

    /**
     * 添加工号前缀
     */
    private String addEmpNoPrefix(RosterTypeEnum type) {
        return (type.equals(RosterTypeEnum.TEMPORARY_WORKER) ? "LS" : "RSK");
    }

    /**
     * 根据id查询员工信息
     */
    public RosterBo getById(Integer id) {
        final LambdaQueryWrapper<RosterBo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RosterBo::getId, id)
                .ne(RosterBo::getStatus, RosterStatusEnum.LEAVE);
        return rosterMapper.selectOne(wrapper);
    }

    /**
     * 修改员工类型
     */
    @Override
    public Integer changeType(RosterChangeTypeDto rosterChangeTypeDto) {
        final RosterBo rosterBo = getById(rosterChangeTypeDto.getId());
        if (VerifyUtils.isEmpty(rosterBo)) {
            GraceException.display("没有对应用户信息");
        }

        rosterBo.setType(rosterChangeTypeDto.getType());
        rosterBo.setEmpNo(generateEmpNo(rosterChangeTypeDto.getType()));

        return rosterMapper.updateById(rosterBo);
    }

    /**
     * 提交
     */
    @Override
    public Integer submit(Integer id) {
        final RosterBo rosterBo = new RosterBo();
        rosterBo.setStatus(1);
        rosterBo.setId(id);
        return rosterMapper.updateById(rosterBo);
    }

    /**
     * 删除id
     */
    @Override
    public Integer deleteById(Integer id) {
        LambdaQueryWrapper<RosterBo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RosterBo::getId, id)
                .eq(RosterBo::getStatus, RosterStatusEnum.SAVE);
        final RosterBo rosterBo = rosterMapper.selectOne(wrapper);
        if (VerifyUtils.isEmpty(rosterBo)) {
            GraceException.display("没有对应用户信息");
        }

        return rosterMapper.deleteById(id);
    }

    /**
     * 分页查询
     */
    @Override
    public Page<RosterVo> PageList(RosterRequest rosterRequest) {
        final Page<RosterBo> page = new Page<>(rosterRequest.getPageNum(), rosterRequest.getPageSize());

        final LambdaQueryWrapper<RosterBo> wrapper = new LambdaQueryWrapper<>();

        String key = rosterRequest.getKey();
        if (StringUtils.isNotBlank(key)) {
            wrapper.like(RosterBo::getName, key)
                    .or().like(RosterBo::getIdentityNumber, key)
                    .or().like(RosterBo::getName, key)
                    .or().like(RosterBo::getPhoneNumber, key)
                    .or().like(RosterBo::getRemark, key)
                    .or().like(RosterBo::getEmpNo, key)
                    .or().like(RosterBo::getUrgencyName, key)
                    .or().like(RosterBo::getUrgencyPhone, key);
        }

        // 政治面貌
        if (VerifyUtils.isNotEmpty(rosterRequest.getPoliticsStatus())) {
            wrapper.eq(RosterBo::getPoliticsStatus, rosterRequest.getPoliticsStatus());
        }
        // 婚姻
        if (VerifyUtils.isNotEmpty(rosterRequest.getMarriageStatus())) {
            wrapper.eq(RosterBo::getMarriageStatus, rosterRequest.getMarriageStatus());
        }
        // 员工类型
        if (VerifyUtils.isNotEmpty(rosterRequest.getType())) {
            wrapper.eq(RosterBo::getType, rosterRequest.getType());
        }
        // 员工状态
        if (VerifyUtils.isNotEmpty(rosterRequest.getStatus())) {
            wrapper.in(RosterBo::getStatus, rosterRequest.getStatus());
        }
        // 学历
        if (VerifyUtils.isNotEmpty(rosterRequest.getEducation())) {
            wrapper.eq(RosterBo::getEducation, rosterRequest.getEducation());
        }
        // 招聘来源
        if (VerifyUtils.isNotEmpty(rosterRequest.getRecruitSource())) {
            wrapper.eq(RosterBo::getRecruitSource, rosterRequest.getRecruitSource());
        }

        // 是否转正
        if (VerifyUtils.isNotEmpty(rosterRequest.getFlagNormal())) {
            if (rosterRequest.getFlagNormal() == 0) {
                wrapper.isNull(RosterBo::getNormalDate);
            } else if (rosterRequest.getFlagNormal() == 1) {
                wrapper.isNotNull(RosterBo::getNormalDate);
            } else {
                GraceException.display("参数错误");
            }

        }

        // 入职时间范围
        if (ArrayUtils.isNotEmpty(rosterRequest.getEntryDate())) {
            wrapper.between(RosterBo::getEntryDate, rosterRequest.getEntryDate()[0], rosterRequest.getEntryDate()[1]);
        }


        // 当月过生人员
        if (VerifyUtils.isNotEmpty(rosterRequest.getOverMonth())) {
            // 使用 SQL 函数直接比较月份
            wrapper.apply("MONTH(birthday) = {0}", rosterRequest.getOverMonth());
        }

        // 转正人员
        if (VerifyUtils.isNotEmpty(rosterRequest.getNormalMonth())) {
            StartAndEndVo monthStartAndEnd = DateUtil.getMonthStartAndEnd(rosterRequest.getNormalMonth());
            wrapper.between(RosterBo::getNormalDate, monthStartAndEnd.getStart(), monthStartAndEnd.getEnd());
        }


        Page<RosterBo> rosterBoPage = switch (rosterRequest.getQueryType()) {
            case NO_BANK_CARD -> rosterMapper.noBankCard(page);
            case NO_SOCIAL_SECURITY -> rosterMapper.noSocialSecurity(page);
            case NO_CONTRACT -> rosterMapper.noSignContract(page);
            case NO_ACCUMULATION_FUND -> rosterMapper.noAccumulationFund(page);
            case CONTRACT_EXPIRED -> {
                final LocalDate localDate = getLocalDate(rosterRequest.getQueryDays());
                yield rosterMapper.contractExpired(page, localDate);
            }
            case IDENTITY_EXPIRED -> {
                final LocalDate localDate = getLocalDate(rosterRequest.getQueryDays());
                wrapper.lt(RosterBo::getIdentityEnd, localDate);
                yield rosterMapper.selectPage(page, wrapper);
            }
            default -> rosterMapper.selectPage(page, wrapper);
        };

        return MybatisPlusUtils.changePageDataClass(rosterBoPage, RosterVo.class);
    }



    // 提取公共方法
    private static LocalDate getLocalDate(int days) {
        try {
            return LocalDate.now().minusDays(days);
        } catch (Exception e) {
            // 异常处理，例如返回默认值或者抛出自定义异常
            return LocalDate.now(); // 示例，默认返回当前日期
        }
    }


}
